package ui.app.com.utile;

import android.util.Log;

import java.io.DataOutputStream;
import java.io.File;

/**
 * 权限操作
 * Created by 郭敏 on 2018/7/20 0020.
 */

public class AdbPower {
    //获取root 权限
    public static boolean runRootCommand(String command) {
        boolean isRoot = false;
        File su = new File("/system/bin/su");
        if (su.exists()) {
            isRoot = runRootCommand(1, command);
        }
        File su1 = new File("/system/xbin/su");
        if (!isRoot && su1.exists()) {
            isRoot = runRootCommand(2, command);
        }
        Log.e("获取root", "/system/bin/su:"+su.exists()+" isRoot:"+isRoot);
        Log.e("获取root", "/system/xbin/su:"+su1.exists()+" isRoot:"+isRoot);
        return isRoot;
    }

    public static boolean runRootCommand(int type, String command) {
        boolean isRoot = false;
        try {
            Process process = null;
            switch (type) {
                case 1:
                    process = Runtime.getRuntime().exec("su");
                    break;
                case 2:
                    process = new ProcessBuilder()
                            .command("/system/xbin/su")
                            .redirectErrorStream(true).start();
                    break;
            }
            if(process==null){
                return isRoot;
            }
            DataOutputStream os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(command + "\n");
            os.writeBytes("exit\n");
            os.flush();
            process.waitFor();
            os.close();
            process.destroy();
            isRoot = true;
            Log.e("获取root权限成功", "---------------");
        } catch (Exception e) {
            Log.e("获取root权限失败", e.getMessage());
        }
        return isRoot;
    }

}
